const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return `${[year, month, day].map(formatNumber).join('/')} ${[hour, minute, second].map(formatNumber).join(':')}`
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : `0${n}`
}
const parseTime = (time, format) => {
	if (!time) return '';
	const cformat = format || 'yyyy-MM-dd hh:mm:ss';
	let date;
	if (typeof time === 'object') {
		date = time;
	} else {
		if ((typeof time === 'string') && (/^[0-9]+$/.test(time))) {
			time = parseInt(time)
		}
		date = new Date(time);
	}
	const map = {
		'M': date.getMonth() + 1, // 月份
		'd': date.getDate(), // 日
		'h': date.getHours(), // 小时
		'm': date.getMinutes(), // 分钟
		's': date.getSeconds(), // 秒
		'q': Math.floor((date.getMonth() + 3) / 3), // 季度
		'S': date.getMilliseconds() // 毫秒
	};

	const time_str = cformat.replace(/([yMdhmsqS])+/g, (all, t) => {
		let v = map[t];
		if (v !== undefined) {
			if (all.length > 1) {
				v = '0' + v;
				v = v.substr(v.length - all.length);
			}
			return v;
		} else if (t === 'y') {
			return (date.getFullYear() + '').substr(4 - all.length);
		}
		return all;
	});
	return time_str;
}
const getRandomColor = () => {
	const r = Math.floor(Math.random() * 256);
	const g = Math.floor(Math.random() * 256);
	const b = Math.floor(Math.random() * 256);
	return {
		r,
		g,
		b,
		'rgb': `rgb(${r},${g},${b})`
	}
}

module.exports = {
  formatTime,
  parseTime,
  getRandomColor
}
